<template>
  <div class="item-list">
    <div 
    class="item"  
    v-for="item in letters" 
    :key="item"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @click="handleClick"
    :ref="item"
    >
    {{item}}
    </div>
  </div>
</template>
<script>
import Bscroll from "better-scroll";
export default {
  name: "CityAlphabet",
  props: {
    cities: Object
  },
  data() {
    return {
      isTouch: false,
      timeId: null,
      startY: 0
    };
  },
  updated() {
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    handleClick(e) {
      this.$emit("change", e.target.innerText);
    },
    handleTouchStart() {
      this.isTouch = true;
    },
    handleTouchMove(e) {
      if (this.isTouch === true) {
        if (this.timeId) {
          clearTimeout(this.timeId);
        }
        this.timeId = setTimeout(() => {
          const touchY = e.touches[0].clientY - 73;
          const index = Math.floor((touchY - this.startY) / 20);
          if (index >= 0 && index < this.letters.length) {
            this.$emit("change", this.letters[index]);
          }
        }, 16);
      }
    },
    handleTouchEnd() {
      this.isTouch = false;
    }
  },
  computed: {
    letters() {
      let letters = [];
      for (let item in this.cities) {
        letters.push(item);
      }
      return letters;
    }
  }
};
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.item-list {
  position: absolute;
  top: 1.58rem;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 0.4rem;

  .item {
    line-height: 0.4rem;
    text-align: center;
    color: $bgColor;
  }
}
</style>
